<template>
	<div class='fx'>
		<Input v-model:value='modelValue' :p='p' :disabled='disabled' @input='onInput' :size='size' />
		<Button class='ml10' @click='onClick' ghost :disabled='btnDisabled || disabled' :size='size'>
			<template v-if='btnDisabled && !disabled'>
				<b class='f14' style='color:red'>{{time}}<i style='margin-left:2px'>s</i></b>
				<span style='margin-left:2px'>后重新获取验证码</span>
			</template> 
			<template v-else>{{txt}}</template>
		</Button>
	</div>
</template>

<script>
	import { ref, watch } from 'vue'
	const Input 		= $.lazy(()=>import('@antd/form/input.vue'))
	const Button 		= $.lazy(()=>import('@antd/button.vue'))
	const isTel = v => /^1[0-9]{10}$/.test(v)
	export default{
		components:{ Input, Button},
		props:{
			value 		: String,
			name 		: String,
			label 		: String,
			form 		: Object,
			p			: { type:String },
			api 		: String,
			labelText 	: { type:String, default:'发送验证码'},
			formRef 	: Object,
			disabled 	: Boolean,
			param		: Object,
			phoneStr 	: { type:String, default:'phone' },
			size 		: [Number, String]
		},
		emits:{
			change:null,
			blur:null,
			click:null,
			'update:value':null
		},
		setup(props, ctx){
			const { api, formRef, phoneStr, labelText, disabled, param } = props
			const modelValue = ref(props.value)
			const defaultTime = 60
			const time = ref(defaultTime)
			const btnDisabled = ref( disabled )
			const txt = ref(labelText)
			
			watch(()=>props.value, value => modelValue.value = value )
			
			return {
				modelValue,
				time,
				txt,
				btnDisabled,
				onInput : value => {
					modelValue.value = value
					ctx.emit('update:value', value)
					ctx.emit('change', { value, row:{ [name]: value } })
				},
				onClick: () => {
					if(btnDisabled.value){ return }
					
					const tel = formRef.getValue(phoneStr)
					
					if(tel === '' || tel === undefined || tel === null){ return $fn.msg.warning('电话不能为空') }
					if(/^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])d{8}$/.test(tel) ){ return $fn.msg.warning('手机号码不合法') }
					
					if( api ){
						btnDisabled.value = true
					}else{
						return $fn.msg.error('请传递验证接口')
					}
					
					$http.post(null,api,{
						param 	: { [phoneStr]:tel, ...param }, 
						token	: false, 
						onAny 	: ()=> { modelValue.value = '' },
						onError	: () => { btnDisabled.value = false }
					}).then(data=>{
						const cleartime = setInterval(()=>{
							time.value --
							txt.value = '后重新获取'
							if(time.value <= 0){
								clearInterval(cleartime);
								time.value = defaultTime
								txt.value = '重新获取验证码'
								btnDisabled.value = false
							}
						},1000)
					})
				}
			}
		}
	}
</script>